import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:flutter_html/flutter_html.dart';
import '../../../common/models/index.dart';

import 'index.dart';

class ShnebaoAssessmentDetialPage extends StatefulWidget {
  const ShnebaoAssessmentDetialPage({super.key});

  @override
  State<ShnebaoAssessmentDetialPage> createState() => _ShnebaoAssessmentDetialPageState();
}

class _ShnebaoAssessmentDetialPageState extends State<ShnebaoAssessmentDetialPage> {
  int _selectedIndex = 0;

  ShnebaoAssessmentDetialController get controller => Get.find<ShnebaoAssessmentDetialController>();

  // 项目详情视图
  Widget _buildProjectDetailView() {
    return Obx(() {
      if (controller.isLoading.value) {
        return const Center(
          child: CircularProgressIndicator(),
        );
      }
      
      if (controller.errorMessage.value.isNotEmpty) {
        return Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Icon(Icons.error_outline, size: 48, color: Colors.red),
              const SizedBox(height: 16),
              Text(
                controller.errorMessage.value,
                style: const TextStyle(fontSize: 16, color: Colors.red),
                textAlign: TextAlign.center,
              ),
              const SizedBox(height: 16),
              ElevatedButton(
                onPressed: controller.refreshProjectDetail,
                child: const Text('重试'),
              ),
            ],
          ),
        );
      }
      
      if (controller.project.value == null) {
        return const Center(
          child: Text('暂无项目信息'),
        );
      }
      
      final project = controller.project.value!;
      return RefreshIndicator(
        onRefresh: controller.refreshProjectDetail,
        child: SingleChildScrollView(
          physics: const AlwaysScrollableScrollPhysics(),
          padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              _buildProjectHeader(project),
              const SizedBox(height: 8),
              _buildProjectInfo(project),
              const SizedBox(height: 8),
              _buildProjectDetails(project),
            ],
          ),
        ),
      );
    });
  }

  // 评审专家视图
  Widget _buildExpertsView() {
    return Obx(() {
      if (controller.isLoading.value) {
        return const Center(
          child: CircularProgressIndicator(),
        );
      }
      
      return RefreshIndicator(
        onRefresh: controller.refreshProjectExperts,
        child: SingleChildScrollView(
          physics: const AlwaysScrollableScrollPhysics(),
          padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
          child: _buildProjectExperts(),
        ),
      );
    });
  }

  // 项目步骤视图
  Widget _buildProjectStepsView() {
    return Obx(() {
      if (controller.isLoadingSteps.value) {
        return const Center(
          child: CircularProgressIndicator(),
        );
      }
      
      if (controller.stepErrorMessage.value.isNotEmpty) {
        return Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Icon(Icons.error_outline, size: 48, color: Colors.red),
              const SizedBox(height: 16),
              Text(
                controller.stepErrorMessage.value,
                style: const TextStyle(fontSize: 16, color: Colors.red),
                textAlign: TextAlign.center,
              ),
              const SizedBox(height: 16),
              ElevatedButton(
                onPressed: controller.refreshProjectSteps,
                child: const Text('重试'),
              ),
            ],
          ),
        );
      }
      
      if (controller.projectSteps.isEmpty) {
        return const Center(
          child: Text('暂无项目步骤信息'),
        );
      }
      
      return RefreshIndicator(
        onRefresh: controller.refreshProjectSteps,
        child: SingleChildScrollView(
          physics: const AlwaysScrollableScrollPhysics(),
          padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 只显示有数据的表
              if (_hasDataInJson(controller.projectSteps['purchaseJson'])) ...[
              _buildStepCard('产品购置明细', Icons.shopping_cart, _buildPurchaseContent()),
              const SizedBox(height: 12),
              ],
              if (_hasDataInJson(controller.projectSteps['softwareJson'])) ...[
              _buildStepCard('软件开发明细', Icons.code, _buildSoftwareContent()),
              const SizedBox(height: 12),
              ],
              if (_hasDataInJson(controller.projectSteps['implementationJson'])) ...[
              _buildStepCard('实施服务明细', Icons.build, _buildImplementationContent()),
              const SizedBox(height: 12),
              ],
              if (_hasDataInJson(controller.projectSteps['cloudJson'])) ...[
              _buildStepCard('市级政务云租用', Icons.cloud, _buildCloudContent()),
              const SizedBox(height: 12),
              ],
              // 预算总表始终显示
              _buildStepCard('预算总表', Icons.calculate, _buildBudgetContent()),
              const SizedBox(height: 20),
            ],
          ),
        ),
      );
    });
  }

  // 项目头部信息
  Widget _buildProjectHeader(ProjectModel project) {
    return Card(
      elevation: 2,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
      child: Container(
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(12),
          gradient: LinearGradient(
            begin: Alignment.topLeft,
            end: Alignment.bottomRight,
            colors: [
              Colors.blue.shade50,
              Colors.white,
            ],
          ),
        ),
        padding: const EdgeInsets.all(12),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                Expanded(
                  child: Text(
                    project.projectName ?? '未知项目',
                    style: TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.bold,
                      color: Colors.blue.shade900,
                    ),
                    maxLines: 2,
                    overflow: TextOverflow.ellipsis,
                  ),
                ),
              ],
            ),
            const SizedBox(height: 8),
            Row(
              children: [
                Container(
                  padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3),
                  decoration: BoxDecoration(
                    color: ProjectModel.getStatusColorByValue(project.status).withValues(alpha: 0.15),
                    borderRadius: BorderRadius.circular(10),
                    border: Border.all(
                      color: ProjectModel.getStatusColorByValue(project.status),
                      width: 1.5,
                    ),
                  ),
                  child: Text(
                    ProjectModel.getStatusTextByValue(project.status),
                    style: TextStyle(
                      color: ProjectModel.getStatusColorByValue(project.status),
                      fontSize: 11,
                      fontWeight: FontWeight.w600,
                    ),
                  ),
                ),
                const SizedBox(width: 8),
                if (project.budgetAmount != null && project.budgetAmount.toString() != 'null')
                  Container(
                    padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3),
                    decoration: BoxDecoration(
                      color: Colors.orange.shade50,
                      borderRadius: BorderRadius.circular(10),
                      border: Border.all(
                        color: Colors.orange.shade300,
                        width: 1,
                      ),
                    ),
                    child: Row(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        Icon(Icons.account_balance_wallet, size: 12, color: Colors.orange.shade700),
                        const SizedBox(width: 4),
                        Text(
                          '${project.budgetAmount}万元',
                          style: TextStyle(
                            fontSize: 11,
                            fontWeight: FontWeight.w600,
                            color: Colors.orange.shade700,
                          ),
                        ),
                      ],
                    ),
                  ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  // 项目基本信息
  Widget _buildProjectInfo(ProjectModel project) {
    return Card(
      elevation: 1,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
      child: Padding(
        padding: const EdgeInsets.all(10),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                Icon(Icons.info_outline, size: 16, color: Colors.blue.shade600),
                const SizedBox(width: 6),
                Text(
                  '基本信息',
                  style: TextStyle(
                    fontSize: 14,
                    fontWeight: FontWeight.bold,
                    color: Colors.blue.shade700,
                  ),
                ),
              ],
            ),
            const SizedBox(height: 8),
            _buildInfoRow('申报部门', project.declareDepartment != 'null' ? project.declareDepartment : null, Icons.business),
            _buildInfoRow('项目编号', project.projectNo != 'null' ? project.projectNo : null, Icons.tag),
            _buildInfoRow('申报时间', project.declareTime != 'null' ? project.declareTime : null, Icons.calendar_today),
            _buildInfoRow('项目联系人', project.projectContact != 'null' ? project.projectContact : null, Icons.person),
            _buildInfoRow('联系电话', project.phone != 'null' ? project.phone : null, Icons.phone),
            _buildInfoRow('项目负责人', project.projectManager != 'null' ? project.projectManager : null, Icons.manage_accounts),
          ],
        ),
      ),
    );
  }

  // 项目详细信息（与Web端预算汇总基本信息一致）
  Widget _buildProjectDetails(ProjectModel project) {
    return Card(
      elevation: 1,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
      child: Padding(
        padding: const EdgeInsets.all(10),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                Icon(Icons.description, size: 16, color: Colors.blue.shade600),
                const SizedBox(width: 6),
                Text(
                  '项目详情',
                  style: TextStyle(
                    fontSize: 14,
                    fontWeight: FontWeight.bold,
                    color: Colors.blue.shade700,
                  ),
                ),
              ],
            ),
            const SizedBox(height: 8),
            // 🔥 背景、现状和必要性（支持富文本表格）
            if (project.background?.isNotEmpty == true && project.background != 'null') ...[
              _buildRichTextSection('背景、现状和必要性', project.background!),
              const SizedBox(height: 6),
            ],
            // 🔥 需求分析（支持富文本表格）
            if (project.requirements?.isNotEmpty == true && project.requirements != 'null') ...[
              _buildRichTextSection('需求分析', project.requirements!),
              const SizedBox(height: 6),
            ],
            // 🔥 建设目标（支持富文本表格）
            if (project.objectives?.isNotEmpty == true && project.objectives != 'null') ...[
              _buildRichTextSection('建设目标', project.objectives!),
              const SizedBox(height: 6),
            ],
            // 🔥 建设方案（支持富文本表格）
            if (project.plan?.isNotEmpty == true && project.plan != 'null') ...[
              _buildRichTextSection('建设方案', project.plan!),
              const SizedBox(height: 6),
            ],
            // 🔥 项目实施方案（支持富文本表格）
            if (project.implementation?.isNotEmpty == true && project.implementation != 'null') ...[
              _buildRichTextSection('项目实施方案', project.implementation!),
              const SizedBox(height: 6),
            ],
            // 🔥 项目预算（支持富文本表格）
            if (project.budget?.isNotEmpty == true && project.budget != 'null') ...[
              _buildRichTextSection('项目预算', project.budget!),
              const SizedBox(height: 6),
            ],
            // 评审建议（如果有）
            if (project.reviewSuggestions?.toString().isNotEmpty == true && project.reviewSuggestions.toString() != 'null') ...[
              _buildRichTextSection('评审建议', project.reviewSuggestions.toString()),
            ],
          ],
        ),
      ),
    );
  }

  // 信息行
  Widget _buildInfoRow(String label, String? value, IconData? icon) {
    // 处理null值或"null"字符串
    final displayValue = (value?.isNotEmpty == true && value != 'null') ? value! : '暂无';
    final isValid = value?.isNotEmpty == true && value != 'null';
    
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 4),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          if (icon != null) ...[
            Icon(icon, size: 14, color: Colors.grey.shade600),
            const SizedBox(width: 6),
          ],
          SizedBox(
            width: 70,
            child: Text(
              label,
              style: TextStyle(
                fontWeight: FontWeight.w500,
                fontSize: 13,
                color: Colors.grey.shade700,
              ),
            ),
          ),
          Expanded(
            child: Text(
              displayValue,
              style: TextStyle(
                fontSize: 13,
                color: isValid ? Colors.black87 : Colors.grey.shade400,
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 🔥 构建富文本详情节（支持HTML表格渲染）
  Widget _buildRichTextSection(String title, String htmlContent) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          title,
          style: TextStyle(
            fontWeight: FontWeight.w600,
            fontSize: 12,
            color: Colors.grey.shade700,
          ),
        ),
        const SizedBox(height: 4),
        Container(
          width: double.infinity,
          padding: const EdgeInsets.all(8),
          decoration: BoxDecoration(
            color: Colors.grey.shade50,
            borderRadius: BorderRadius.circular(6),
            border: Border.all(color: Colors.grey.shade200),
          ),
          child: Html(
            data: htmlContent,
            style: {
              "body": Style(
                margin: Margins.zero,
                padding: HtmlPaddings.zero,
                fontSize: FontSize(13),
                lineHeight: const LineHeight(1.4),
                color: Colors.grey.shade800,
              ),
              // 🔥 表格样式 - 与Web端一致
              "table": Style(
                border: Border.all(color: Colors.grey.shade300),
                width: Width(100, Unit.percent),
                margin: Margins.symmetric(vertical: 8),
              ),
              "th": Style(
                padding: HtmlPaddings.all(8),
                backgroundColor: Colors.grey.shade200,
                border: Border.all(color: Colors.grey.shade300),
                fontSize: FontSize(12),
                fontWeight: FontWeight.bold,
                textAlign: TextAlign.center,
              ),
              "td": Style(
                padding: HtmlPaddings.all(8),
                border: Border.all(color: Colors.grey.shade300),
                fontSize: FontSize(12),
                textAlign: TextAlign.left,
              ),
              "thead": Style(
                backgroundColor: Colors.grey.shade100,
              ),
              "tr": Style(
                border: Border.all(color: Colors.grey.shade300),
              ),
              // 列表样式
              "ul": Style(
                padding: HtmlPaddings.only(left: 16),
                margin: Margins.symmetric(vertical: 4),
              ),
              "ol": Style(
                padding: HtmlPaddings.only(left: 16),
                margin: Margins.symmetric(vertical: 4),
              ),
              "li": Style(
                margin: Margins.only(bottom: 2),
                fontSize: FontSize(12),
              ),
              // 段落样式
              "p": Style(
                margin: Margins.symmetric(vertical: 4),
                fontSize: FontSize(12),
              ),
              "div": Style(
                margin: Margins.symmetric(vertical: 2),
              ),
              // 标题样式
              "h1": Style(fontSize: FontSize(16), fontWeight: FontWeight.bold),
              "h2": Style(fontSize: FontSize(15), fontWeight: FontWeight.bold),
              "h3": Style(fontSize: FontSize(14), fontWeight: FontWeight.bold),
              "h4": Style(fontSize: FontSize(13), fontWeight: FontWeight.bold),
              // 强调样式
              "b": Style(fontWeight: FontWeight.bold),
              "strong": Style(fontWeight: FontWeight.bold),
              "i": Style(fontStyle: FontStyle.italic),
              "em": Style(fontStyle: FontStyle.italic),
              "u": Style(textDecoration: TextDecoration.underline),
            },
          ),
        ),
      ],
    );
  }

  // 项目专家列表
  Widget _buildProjectExperts() {
    return Obx(() {
      return Card(
        elevation: 1,
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
        child: Padding(
          padding: const EdgeInsets.all(10),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  Icon(Icons.people, size: 16, color: Colors.blue.shade600),
                  const SizedBox(width: 6),
                  Text(
                    '评审专家列表',
                    style: TextStyle(
                      fontSize: 14,
                      fontWeight: FontWeight.bold,
                      color: Colors.blue.shade700,
                    ),
                  ),
                  const Spacer(),
                  if (controller.isLoadingExperts.value)
                    SizedBox(
                      width: 14,
                      height: 14,
                      child: CircularProgressIndicator(strokeWidth: 2, color: Colors.blue.shade600),
                    )
                  else
                    IconButton(
                      icon: Icon(Icons.refresh, size: 16, color: Colors.grey.shade600),
                      onPressed: controller.refreshProjectExperts,
                      tooltip: '刷新专家列表',
                      padding: EdgeInsets.zero,
                      constraints: const BoxConstraints(),
                    ),
                ],
              ),
              const SizedBox(height: 8),
              
              if (controller.expertErrorMessage.value.isNotEmpty)
                Container(
                  padding: const EdgeInsets.all(8),
                  decoration: BoxDecoration(
                    color: Colors.red.shade50,
                    borderRadius: BorderRadius.circular(6),
                    border: Border.all(color: Colors.red.shade200),
                  ),
                  child: Row(
                    children: [
                      Icon(Icons.error_outline, color: Colors.red.shade600, size: 16),
                      const SizedBox(width: 8),
                      Expanded(
                        child: Text(
                          controller.expertErrorMessage.value,
                          style: TextStyle(color: Colors.red.shade600, fontSize: 12),
                        ),
                      ),
                      TextButton(
                        onPressed: controller.refreshProjectExperts,
                        style: TextButton.styleFrom(
                          padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                          minimumSize: Size.zero,
                          tapTargetSize: MaterialTapTargetSize.shrinkWrap,
                        ),
                        child: const Text('重试', style: TextStyle(fontSize: 12)),
                      ),
                    ],
                  ),
                )
              else if (controller.projectExperts.isEmpty && !controller.isLoadingExperts.value)
                Container(
                  padding: const EdgeInsets.all(10),
                  child: Row(
                    children: [
                      Icon(Icons.info_outline, color: Colors.grey.shade600, size: 16),
                      const SizedBox(width: 8),
                      Text(
                        '暂无评审专家信息',
                        style: TextStyle(color: Colors.grey.shade600, fontSize: 12),
                      ),
                    ],
                  ),
                )
              else
                Builder(
                  builder: (context) {
                    // 将当前登录的专家排在第一位
                    final experts = controller.projectExperts.toList();
                    final currentExpertId = controller.currentExpertId;
                    
                    // 找到当前专家的索引
                    final currentExpertIndex = experts.indexWhere(
                      (expert) => expert.expertId == currentExpertId,
                    );
                    
                    // 如果找到当前专家且不在第一位，则移到第一位
                    if (currentExpertIndex > 0) {
                      final currentExpert = experts.removeAt(currentExpertIndex);
                      experts.insert(0, currentExpert);
                    }
                    
                    return ListView.separated(
                      shrinkWrap: true,
                      physics: const NeverScrollableScrollPhysics(),
                      itemCount: experts.length,
                      separatorBuilder: (context, index) => Divider(height: 12, color: Colors.grey.shade200),
                      itemBuilder: (context, index) {
                        final expert = experts[index];
                        return _buildExpertItem(expert);
                      },
                    );
                  },
                ),
            ],
          ),
        ),
      );
    });
  }

  // 专家项目
  Widget _buildExpertItem(ProjectExpert expert) {
    final isCurrentExpert = expert.expertId == controller.currentExpertId;
    final hasReviewed = _isExpertReviewed(expert);
    
    return Container(
      padding: const EdgeInsets.all(10),
      decoration: BoxDecoration(
        color: isCurrentExpert ? Colors.blue.shade50 : Colors.grey.shade50,
        borderRadius: BorderRadius.circular(8),
        border: Border.all(
          color: isCurrentExpert ? Colors.blue.shade300 : Colors.grey.shade200,
          width: isCurrentExpert ? 2 : 1,
        ),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 专家基本信息行
          Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 专家头像
              CircleAvatar(
                radius: 16,
                backgroundColor: isCurrentExpert ? Colors.blue.shade600 : Colors.blue.shade200,
                child: Text(
                  expert.expertName?.isNotEmpty == true 
                      ? expert.expertName!.substring(0, 1).toUpperCase()
                      : '?',
                  style: TextStyle(
                    color: isCurrentExpert ? Colors.white : Colors.blue.shade800,
                    fontWeight: FontWeight.bold,
                    fontSize: 14,
                  ),
                ),
              ),
              const SizedBox(width: 8),
              
              // 专家信息
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      children: [
                        Flexible(
                          child: Text(
                            expert.expertName ?? '未知专家',
                            style: TextStyle(
                              fontSize: 14,
                              fontWeight: FontWeight.w600,
                              color: isCurrentExpert ? Colors.blue.shade900 : Colors.black87,
                            ),
                            maxLines: 1,
                            overflow: TextOverflow.ellipsis,
                          ),
                        ),
                        if (isCurrentExpert) ...[
                          const SizedBox(width: 4),
                          Container(
                            padding: const EdgeInsets.symmetric(horizontal: 5, vertical: 1),
                            decoration: BoxDecoration(
                              color: Colors.blue.shade600,
                              borderRadius: BorderRadius.circular(3),
                            ),
                            child: const Text(
                              '我',
                              style: TextStyle(
                                fontSize: 10,
                                color: Colors.white,
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                          ),
                        ],
                      ],
                    ),
                    const SizedBox(height: 2),
                    if (expert.corpName?.isNotEmpty == true && expert.corpName != 'null')
                      Text(
                        expert.corpName!,
                        style: TextStyle(
                          fontSize: 12,
                          color: Colors.grey.shade600,
                        ),
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                      ),
                    const SizedBox(height: 3),
                    if (expert.officialCapacity?.isNotEmpty == true && expert.officialCapacity != 'null')
                      Container(
                        padding: const EdgeInsets.symmetric(horizontal: 5, vertical: 2),
                        decoration: BoxDecoration(
                          color: Colors.orange.shade100,
                          borderRadius: BorderRadius.circular(3),
                        ),
                        child: Text(
                          expert.officialCapacity!,
                          style: TextStyle(
                            fontSize: 10,
                            color: Colors.orange.shade800,
                            fontWeight: FontWeight.w500,
                          ),
                        ),
                      ),
                  ],
                ),
              ),
              
              // 状态指示器
              Container(
                padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 3),
                decoration: BoxDecoration(
                  color: hasReviewed ? Colors.green.shade50 : Colors.grey.shade200,
                  borderRadius: BorderRadius.circular(10),
                  border: Border.all(
                    color: hasReviewed ? Colors.green.shade400 : Colors.grey.shade400,
                  ),
                ),
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Container(
                      width: 6,
                      height: 6,
                      decoration: BoxDecoration(
                        color: hasReviewed ? Colors.green : Colors.grey.shade500,
                        shape: BoxShape.circle,
                      ),
                    ),
                    const SizedBox(width: 4),
                    Text(
                      hasReviewed ? '已评审' : '待评审',
                      style: TextStyle(
                        fontSize: 10,
                        fontWeight: FontWeight.w500,
                        color: hasReviewed ? Colors.green.shade700 : Colors.grey.shade700,
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
          
          // 如果已评审，显示评审意见和签名
          if (hasReviewed) ...[
            const SizedBox(height: 8),
            Container(
              padding: const EdgeInsets.all(8),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(6),
                border: Border.all(color: Colors.grey.shade200),
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // 评审意见
                  if (expert.reviewNote?.isNotEmpty == true && expert.reviewNote != 'null') ...[
                    Row(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Icon(Icons.comment_outlined, size: 12, color: Colors.blue.shade600),
                        const SizedBox(width: 4),
                        Expanded(
                          child: Text(
                            expert.reviewNote!,
                            style: TextStyle(
                              fontSize: 12,
                              color: Colors.grey.shade800,
                              height: 1.3,
                            ),
                          ),
                        ),
                      ],
                    ),
                    const SizedBox(height: 6),
                  ],
                  
                  // 签名和时间
                  Row(
                    children: [
                      Icon(Icons.edit_note, size: 12, color: Colors.green.shade600),
                      const SizedBox(width: 4),
                      Text(
                        '已签名',
                        style: TextStyle(
                          fontSize: 11,
                          color: Colors.green.shade700,
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                      if (expert.reviewSignTime != null && expert.reviewSignTime! > 0) ...[
                        const SizedBox(width: 6),
                        Text(
                          _formatTimestamp(expert.reviewSignTime!),
                          style: TextStyle(
                            fontSize: 10,
                            color: Colors.grey.shade500,
                          ),
                        ),
                      ],
                    ],
                  ),
                ],
              ),
            ),
          ],
        ],
      ),
    );
  }
  
  /// 格式化时间戳
  String _formatTimestamp(int timestamp) {
    final date = DateTime.fromMillisecondsSinceEpoch(timestamp);
    final now = DateTime.now();
    final diff = now.difference(date);
    
    if (diff.inDays > 0) {
      return '${diff.inDays}天前';
    } else if (diff.inHours > 0) {
      return '${diff.inHours}小时前';
    } else if (diff.inMinutes > 0) {
      return '${diff.inMinutes}分钟前';
    } else {
      return '刚刚';
    }
  }



  /// 判断专家是否已完成评审
  /// 检查reviewStatus或者是否有签名
  bool _isExpertReviewed(ProjectExpert expert) {
    // 优先检查reviewStatus
    if (expert.reviewStatus == 1) {
      return true;
    }
    
    // 如果reviewStatus不是1，检查是否有签名
    // 有签名图片路径且不为空，说明已经评审
    if (expert.reviewSign != null && 
        expert.reviewSign!.isNotEmpty && 
        expert.reviewSign != 'null') {
      return true;
    }
    
    return false;
  }

  // ==================== 项目步骤相关方法 ====================
  
  /// 判断JSON字符串是否包含有效数据
  bool _hasDataInJson(dynamic jsonStr) {
    if (jsonStr == null || jsonStr.toString().isEmpty) {
      return false;
    }
    
    try {
      final data = jsonDecode(jsonStr.toString());
      if (data == null) return false;
      
      // 检查是否有categories字段且不为空
      if (data is Map<String, dynamic>) {
        if (data.containsKey('categories')) {
          final categories = data['categories'];
          if (categories == null) return false;
          
          // categories可能是Map或List
          if (categories is Map) {
            // 检查Map中是否有任何有效数据
            return categories.values.any((category) {
              if (category is Map && category.containsKey('items')) {
                final items = category['items'];
                return items is List && items.isNotEmpty;
              }
              return false;
            });
          } else if (categories is List) {
            return categories.isNotEmpty;
          }
        }
        
        // 检查其他可能的数据结构（如systems, renovationItems等）
        if (data.containsKey('systems')) {
          final systems = data['systems'];
          return systems is List && systems.isNotEmpty;
        }
        if (data.containsKey('renovationItems')) {
          final items = data['renovationItems'];
          return items is List && items.isNotEmpty;
        }
      }
      
      return false;
    } catch (e) {
      debugPrint('❌ 检查JSON数据失败: $e');
      return false;
    }
  }
  
  /// 构建步骤卡片（适配屏幕宽度，内容可左右滚动）
  Widget _buildStepCard(String title, IconData icon, Widget content) {
    return Card(
      elevation: 1,
      margin: EdgeInsets.zero, // 移除Card默认margin
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 标题区域 - 固定显示
          Container(
            width: double.infinity, // 充满屏幕宽度
            padding: const EdgeInsets.all(12),
            decoration: BoxDecoration(
              color: Colors.blue.shade50,
              borderRadius: const BorderRadius.only(
                topLeft: Radius.circular(10),
                topRight: Radius.circular(10),
              ),
            ),
            child: Row(
              children: [
                Icon(icon, size: 18, color: Colors.blue.shade700),
                const SizedBox(width: 8),
                Text(
                  title,
                  style: TextStyle(
                    fontSize: 15,
                    fontWeight: FontWeight.bold,
                    color: Colors.blue.shade700,
                  ),
                ),
                const Spacer(),
                // 添加滑动提示图标
                Icon(Icons.swipe, size: 16, color: Colors.blue.shade400),
              ],
            ),
          ),
          // 内容区域 - 可左右滚动，无左右padding
          SizedBox(
            width: double.infinity, // 充满屏幕宽度
            child: Padding(
              padding: const EdgeInsets.symmetric(vertical: 12), // 只保留上下padding
              child: content,
            ),
          ),
        ],
      ),
    );
  }

  /// 构建产品购置明细内容
  Widget _buildPurchaseContent() {
    try {
      final purchaseJsonStr = controller.projectSteps['purchaseJson'];
      if (purchaseJsonStr == null || purchaseJsonStr.isEmpty) {
        return _buildEmptyContent('暂无产品购置明细');
      }
      
      // 解析JSON字符串
      final purchaseData = jsonDecode(purchaseJsonStr) as Map<String, dynamic>;
      final categories = purchaseData['categories'] as Map<String, dynamic>?;
      
      if (categories == null || categories.isEmpty) {
        return _buildEmptyContent('暂无产品购置明细');
      }
      
      // 收集所有有效数据（过滤掉数量为0或总计为0的项）
      final allItems = <Map<String, dynamic>>[];
      categories.forEach((categoryName, categoryData) {
        if (categoryData is Map<String, dynamic>) {
          final items = categoryData['items'] as List?;
          if (items != null) {
            for (var item in items) {
              if (item is Map<String, dynamic>) {
                // 只显示数量>0或总计>0的项
                final quantity = (item['数量'] is num) ? item['数量'] as num : 0;
                final total = (item['总计'] is num) ? item['总计'] as num : 0;
                if (quantity > 0 || total > 0) {
                allItems.add({
                  'category': categoryName,
                  'data': item,
                });
                }
              }
            }
          }
        }
      });
      
      if (allItems.isEmpty) {
        return _buildEmptyContent('暂无产品购置明细');
      }
      
      return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 表格数据
          _buildDataTable(
            headers: ['序号', '产品名称', '参考品牌', '参考型号', '配置要求', '政府采购编号', '是否国产', '单价(万元)', '数量', '总计(万元)', '备注'],
            rows: List.generate(allItems.length, (index) {
              final item = allItems[index];
              final data = item['data'] as Map<String, dynamic>;
              return [
                Text('${index + 1}', style: const TextStyle(fontSize: 12)),
                Text(data['产品名称'] ?? '', style: const TextStyle(fontSize: 12)),
                Text(data['参考品牌'] ?? '', style: const TextStyle(fontSize: 12)),
                Text(data['参考型号'] ?? '', style: const TextStyle(fontSize: 12)),
                Text(data['配置要求'] ?? '', style: const TextStyle(fontSize: 12)),
                Text(data['政府采购编号'] ?? '', style: const TextStyle(fontSize: 12)),
                Text(data['是否国产'] ?? '是', style: const TextStyle(fontSize: 12)),
                Text('${data['单价'] ?? 0}', style: const TextStyle(fontSize: 12)),
                Text('${data['数量'] ?? 0}', style: const TextStyle(fontSize: 12)),
                Text('${data['总计'] ?? 0}', style: const TextStyle(fontSize: 12, fontWeight: FontWeight.bold)),
                Text(data['备注'] ?? '', style: const TextStyle(fontSize: 12)),
              ];
            }),
            categoryColumn: 0,
            categoryData: allItems.map((item) => item['category'] as String).toList(),
          ),
        ],
      );
    } catch (e) {
      debugPrint('❌ 解析产品购置数据失败: $e');
      return _buildEmptyContent('数据解析失败');
    }
  }

  /// 构建软件开发明细内容
  Widget _buildSoftwareContent() {
    try {
      final softwareJsonStr = controller.projectSteps['softwareJson'];
      if (softwareJsonStr == null || softwareJsonStr.isEmpty) {
        return _buildEmptyContent('暂无软件开发明细');
      }
      
      // 解析JSON字符串
      final softwareData = jsonDecode(softwareJsonStr) as Map<String, dynamic>;
      final systems = softwareData['systems'] as List?;
      
      if (systems == null || systems.isEmpty) {
        return _buildEmptyContent('暂无软件开发明细');
      }
      
      // 收集所有有效模块（过滤掉工作量为0或开发费用为0的项）
      final allModules = <Map<String, dynamic>>[];
      for (var system in systems) {
        if (system is Map<String, dynamic>) {
          final systemName = system['name'] ?? '';
          final subsystems = system['subsystems'] as List?;
          if (subsystems != null) {
            for (var subsystem in subsystems) {
              if (subsystem is Map<String, dynamic>) {
                final subsystemName = subsystem['name'] ?? '';
                final modules = subsystem['modules'] as List?;
                if (modules != null) {
                  for (var module in modules) {
                    if (module is Map<String, dynamic>) {
                      // 只显示工作量>0或开发费用>0的项
                      final workload = (module['workload'] is num) ? module['workload'] as num : 0;
                      final amount = (module['amount'] is num) ? module['amount'] as num : 0;
                      if (workload > 0 || amount > 0) {
                      allModules.add({
                        'system': systemName,
                        'subsystem': subsystemName,
                        'data': module,
                      });
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
      
      if (allModules.isEmpty) {
        return _buildEmptyContent('暂无软件开发明细');
      }
      
      return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 表格数据
          _buildDataTable(
            headers: ['序号', '子系统', '模块名称', '工作量', '单价(人月)', '开发费用', '备注'],
            rows: List.generate(allModules.length, (index) {
              final item = allModules[index];
              final data = item['data'] as Map<String, dynamic>;
              return [
                Text('${index + 1}', style: const TextStyle(fontSize: 12)),
                Text(item['subsystem'] ?? '', style: const TextStyle(fontSize: 12)),
                Text(data['name'] ?? '', style: const TextStyle(fontSize: 12)),
                Text('${data['workload'] ?? 0}', style: const TextStyle(fontSize: 12)),
                Text('${data['price'] ?? 0}', style: const TextStyle(fontSize: 12)),
                Text('${data['amount'] ?? 0}', style: const TextStyle(fontSize: 12, fontWeight: FontWeight.bold)),
                Text(data['note'] ?? '', style: const TextStyle(fontSize: 12)),
              ];
            }),
            categoryColumn: 0,
            categoryData: allModules.map((item) => item['system'] as String).toList(),
          ),
        ],
      );
    } catch (e) {
      debugPrint('❌ 解析软件开发数据失败: $e');
      return _buildEmptyContent('数据解析失败');
    }
  }

  /// 构建实施服务明细内容
  Widget _buildImplementationContent() {
    try {
      final implementationJsonStr = controller.projectSteps['implementationJson'];
      if (implementationJsonStr == null || implementationJsonStr.isEmpty) {
        return _buildEmptyContent('暂无实施服务明细');
      }
      
      // 解析JSON字符串
      final implementationData = jsonDecode(implementationJsonStr) as Map<String, dynamic>;
      final renovationItems = implementationData['renovationItems'] as List?;
      
      if (renovationItems == null || renovationItems.isEmpty) {
        return _buildEmptyContent('暂无实施服务明细');
      }
      
      // 过滤掉金额为0的项，只显示有内容的数据
      final validItems = renovationItems.where((item) {
        if (item is Map<String, dynamic>) {
          final amount = (item['amount'] is num) ? item['amount'] as num : 0;
          return amount > 0;
        }
        return false;
      }).toList();
      
      if (validItems.isEmpty) {
        return _buildEmptyContent('暂无实施服务明细');
      }
      
      return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 表格数据
          _buildDataTable(
            headers: ['序号', '服务项目', '单位', '工程量', '单价', '工程费用', '备注'],
            rows: List.generate(validItems.length, (index) {
              final item = validItems[index] as Map<String, dynamic>;
              return [
                Text('${index + 1}', style: const TextStyle(fontSize: 12)),
                Text(item['name'] ?? '', style: const TextStyle(fontSize: 12)),
                Text(item['unit'] ?? '', style: const TextStyle(fontSize: 12)),
                Text('${item['quantity'] ?? 0}', style: const TextStyle(fontSize: 12)),
                Text('${item['price'] ?? 0}', style: const TextStyle(fontSize: 12)),
                Text('${item['amount'] ?? 0}', style: const TextStyle(fontSize: 12, fontWeight: FontWeight.bold)),
                Text(item['note'] ?? '', style: const TextStyle(fontSize: 12)),
              ];
            }),
          ),
        ],
      );
    } catch (e) {
      debugPrint('❌ 解析实施服务数据失败: $e');
      return _buildEmptyContent('数据解析失败');
    }
  }

  /// 构建云服务明细内容
  Widget _buildCloudContent() {
    try {
      final cloudJsonStr = controller.projectSteps['cloudJson'];
      if (cloudJsonStr == null || cloudJsonStr.isEmpty) {
        return _buildEmptyContent('暂无云服务明细');
      }
      
      // 解析JSON字符串
      final cloudData = jsonDecode(cloudJsonStr) as Map<String, dynamic>;
      final categories = cloudData['categories'] as List?;
      
      if (categories == null || categories.isEmpty) {
        return _buildEmptyContent('暂无云服务明细');
      }
      
      // 收集所有有效服务（过滤掉金额为0的项）
      final allServices = <Map<String, dynamic>>[];
      for (var category in categories) {
        if (category is Map<String, dynamic>) {
          final categoryName = category['name'] ?? '';
          final services = category['services'] as List?;
          if (services != null) {
            for (var service in services) {
              if (service is Map<String, dynamic>) {
                // 只显示费用合计>0的项
                final total = (service['total'] is num) ? service['total'] as num : 0;
                if (total > 0) {
                allServices.add({
                  'category': categoryName,
                  'data': service,
                });
                }
              }
            }
          }
        }
      }
      
      if (allServices.isEmpty) {
        return _buildEmptyContent('暂无云服务明细');
      }
      
      return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 表格数据
          _buildDataTable(
            headers: ['序号', '服务名称', '项目', '单位', '单价', '数量', '租用期限', '费用合计', '备注'],
            rows: List.generate(allServices.length, (index) {
              final item = allServices[index];
              final data = item['data'] as Map<String, dynamic>;
              return [
                Text('${index + 1}', style: const TextStyle(fontSize: 12)),
                Text(data['name'] ?? '', style: const TextStyle(fontSize: 12)),
                Text(data['item'] ?? '', style: const TextStyle(fontSize: 12)),
                Text(data['unit'] ?? '', style: const TextStyle(fontSize: 12)),
                Text('${data['price'] ?? 0}', style: const TextStyle(fontSize: 12)),
                Text('${data['quantity'] ?? 0}', style: const TextStyle(fontSize: 12)),
                Text(data['period'] ?? '', style: const TextStyle(fontSize: 12)),
                Text('${data['total'] ?? 0}', style: const TextStyle(fontSize: 12, fontWeight: FontWeight.bold)),
                Text(data['note'] ?? '', style: const TextStyle(fontSize: 12)),
              ];
            }),
            categoryColumn: 0,
            categoryData: allServices.map((item) => item['category'] as String).toList(),
          ),
        ],
      );
    } catch (e) {
      debugPrint('❌ 解析云服务数据失败: $e');
      return _buildEmptyContent('数据解析失败');
    }
  }

  /// 构建预算总表内容
  Widget _buildBudgetContent() {
    try {
      final budgetJsonStr = controller.projectSteps['budgetJson'];
      if (budgetJsonStr == null || budgetJsonStr.isEmpty) {
        return _buildEmptyContent('暂无预算总表');
      }
      
      // 解析JSON字符串
      final budgetData = jsonDecode(budgetJsonStr) as Map<String, dynamic>;
      debugPrint('📊 预算数据结构: ${budgetData.keys}');
      
      final totalAmount = budgetData['totalAmount'] ?? 0;
      
      // 🔥 categories 可能是 Map 或 List，需要分别处理
      final categoriesData = budgetData['categories'];
      
      if (categoriesData == null) {
        return _buildEmptyContent('暂无预算总表');
      }
      
      final categoryDetails = <Map<String, dynamic>>[];
      
      // 处理 Map 格式的 categories（预算总表显示所有类别及其明细项）
      if (categoriesData is Map<String, dynamic>) {
        debugPrint('📊 预算数据categories是Map格式');
        final categoryOrder = ['hardware', 'software', 'engineering', 'others'];
        final categoryNames = {
          'hardware': '一、硬件类费用',
          'software': '二、软件类费用',
          'engineering': '三、配套工程类费用',
          'others': '四、相关其他费用',
        };
        
        // 按固定顺序显示所有类别
        for (var key in categoryOrder) {
          final categoryData = categoriesData[key];
          if (categoryData is Map<String, dynamic>) {
            final subtotal = categoryData['subtotal'] ?? 0;
            final items = categoryData['items'] as List?;
            categoryDetails.add({
              'name': categoryNames[key] ?? key,
              'subtotal': subtotal,
                'items': items ?? [],
              });
          } else {
            // 如果没有数据，也要显示该类别（金额为0）
            categoryDetails.add({
              'name': categoryNames[key] ?? key,
              'subtotal': 0,
              'items': [],
            });
          }
        }
      } 
      // 处理 List 格式的 categories
      else if (categoriesData is List) {
        debugPrint('📊 预算数据categories是List格式，共 ${categoriesData.length} 项');
        for (var category in categoriesData) {
          if (category is Map<String, dynamic>) {
            final name = category['name'] ?? category['类别名称'] ?? '';
            final subtotal = category['subtotal'] ?? category['小计'] ?? 0;
            final items = category['items'] as List?;
            categoryDetails.add({
                'name': name,
              'subtotal': subtotal,
                'items': items ?? [],
              });
          }
        }
      } else {
        debugPrint('❌ 未知的categories数据格式: ${categoriesData.runtimeType}');
        return _buildEmptyContent('预算数据格式不支持');
      }
      
      // 构建完整的预算表格
      return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 详细预算表格
          _buildDetailedBudgetTable(categoryDetails, totalAmount),
        ],
      );
    } catch (e, stackTrace) {
      debugPrint('❌ 解析预算数据失败: $e');
      debugPrint('📊 堆栈跟踪: $stackTrace');
      return _buildEmptyContent('数据解析失败');
    }
  }
  
  /// 构建详细的预算表格（适配屏幕宽度，内容可左右滚动）
  Widget _buildDetailedBudgetTable(List<Map<String, dynamic>> categoryDetails, num totalAmount) {
    int globalIndex = 1;
    final List<Widget> tableRows = [];
    
    // 遍历每个类别
    for (var category in categoryDetails) {
      final categoryName = category['name'] as String;
      final subtotal = category['subtotal'] as num;
      final items = category['items'] as List;
      
      // 添加类别标题行
      tableRows.add(
          Container(
          margin: const EdgeInsets.only(bottom: 8, top: 8),
          padding: const EdgeInsets.all(12),
            decoration: BoxDecoration(
            color: Colors.blue.shade50,
            borderRadius: BorderRadius.circular(8),
            border: Border.all(color: Colors.blue.shade200),
            ),
            child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(
                categoryName,
                      style: TextStyle(
                  fontSize: 15,
                  fontWeight: FontWeight.bold,
                  color: Colors.blue.shade800,
                      ),
                    ),
                    Text(
                '小计: ¥${subtotal.toStringAsFixed(2)}',
                      style: TextStyle(
                  fontSize: 14,
                        fontWeight: FontWeight.bold,
                  color: Colors.blue.shade700,
                      ),
                    ),
                  ],
                ),
            ),
      );
      
      // 添加该类别下的所有明细项
      if (items.isNotEmpty) {
        for (var item in items) {
          if (item is Map<String, dynamic>) {
            final itemName = item['name'] ?? '';
            final itemAmount = item['amount'] ?? item['price'] ?? 0;
            
            // ✅ 显示所有项目，包括金额为0的
            tableRows.add(
                    Container(
                padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 12),
                      decoration: BoxDecoration(
                  border: Border(
                    bottom: BorderSide(color: Colors.grey.shade200),
                        ),
                      ),
                      child: Row(
                        children: [
                    // 序号
                    SizedBox(
                      width: 40,
                      child: Text(
                        '$globalIndex',
                        style: TextStyle(
                          fontSize: 13,
                          color: Colors.grey.shade600,
                        ),
                        textAlign: TextAlign.center,
                      ),
                    ),
                    const SizedBox(width: 8),
                    // 费用名称
                    Expanded(
                      flex: 3,
                      child: Text(
                        itemName,
                            style: const TextStyle(
                          fontSize: 13,
                              color: Colors.black87,
                            ),
                          ),
                    ),
                    const SizedBox(width: 8),
                    // 申报额
                    SizedBox(
                      width: 100,
                      child: Text(
                        '¥${(itemAmount as num).toStringAsFixed(2)}',
                        style: const TextStyle(
                          fontSize: 13,
                          color: Colors.black87,
                          fontWeight: FontWeight.w500,
                        ),
                        textAlign: TextAlign.right,
                            ),
                          ),
                        ],
                      ),
                    ),
            );
            globalIndex++;
          }
        }
      } else {
        // 如果没有明细项，显示提示
        tableRows.add(
                      Padding(
            padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 12),
                        child: Text(
              '暂无明细项目',
                          style: TextStyle(
                            fontSize: 12,
                color: Colors.grey.shade500,
                fontStyle: FontStyle.italic,
              ),
            ),
          ),
        );
      }
    }
    
    // 添加总计行（放在最后）
    tableRows.add(
      Container(
        margin: const EdgeInsets.only(top: 16),
        padding: const EdgeInsets.all(16),
        decoration: BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topLeft,
            end: Alignment.bottomRight,
            colors: [Colors.indigo.shade50, Colors.indigo.shade100],
                          ),
          borderRadius: BorderRadius.circular(12),
          border: Border.all(color: Colors.indigo.shade300, width: 2),
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Row(
              children: [
                Icon(Icons.calculate_outlined, size: 24, color: Colors.indigo.shade700),
                const SizedBox(width: 12),
                Text(
                  '升级改造费用合计',
                  style: TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.bold,
                    color: Colors.indigo.shade900,
                        ),
                      ),
                  ],
                ),
            Text(
              '¥${totalAmount.toStringAsFixed(2)}',
              style: TextStyle(
                fontSize: 20,
                fontWeight: FontWeight.bold,
                color: Colors.indigo.shade900,
              ),
            ),
        ],
        ),
      ),
    );
    
    return Container(
      width: double.infinity, // 充满父容器宽度
      padding: const EdgeInsets.symmetric(horizontal: 12), // 左右留白
      child: Container(
        decoration: BoxDecoration(
          border: Border.all(color: Colors.grey.shade300),
          borderRadius: BorderRadius.circular(8),
          color: Colors.white, // 背景色
        ),
        child: Column(
          children: tableRows,
        ),
      ),
    );
  }

  /// 构建空内容提示
  Widget _buildEmptyContent(String message) {
    return Container(
      padding: const EdgeInsets.all(20),
      alignment: Alignment.center,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(Icons.info_outline, size: 16, color: Colors.grey.shade400),
          const SizedBox(width: 8),
          Text(
            message,
            style: TextStyle(
              fontSize: 14,
              color: Colors.grey.shade400,
            ),
          ),
        ],
      ),
    );
  }

  /// 构建数据表格（适配屏幕宽度，内容可左右滚动）
  Widget _buildDataTable({
    required List<String> headers,
    required List<List<Widget>> rows,
    int? categoryColumn,
    List<String>? categoryData,
  }) {
    return Container(
      width: double.infinity, // 充满父容器宽度
      padding: const EdgeInsets.symmetric(horizontal: 12), // 左右留白
      child: SingleChildScrollView(
        scrollDirection: Axis.horizontal, // 横向滚动
        physics: const BouncingScrollPhysics(), // 弹性滚动效果
        child: Container(
          decoration: BoxDecoration(
            border: Border.all(color: Colors.grey.shade300),
            borderRadius: BorderRadius.circular(8),
            color: Colors.white, // 背景色
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
            // 表头
            Container(
              decoration: BoxDecoration(
                color: Colors.grey.shade100,
                borderRadius: const BorderRadius.only(
                  topLeft: Radius.circular(8),
                  topRight: Radius.circular(8),
                ),
              ),
              child: Row(
                children: headers.map((header) {
                  return Container(
                    width: _getColumnWidth(header),
                    padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 12),
                    child: Text(
                      header,
                      style: const TextStyle(
                        fontSize: 13,
                        fontWeight: FontWeight.bold,
                        color: Colors.black87,
                      ),
                      textAlign: TextAlign.center,
                    ),
                  );
                }).toList(),
              ),
            ),
            
            // 表格内容
            ...List.generate(rows.length, (rowIndex) {
              final row = rows[rowIndex];
              String? currentCategory;
              
              // 检查是否需要显示分类标题
              if (categoryColumn != null && 
                  categoryData != null && 
                  rowIndex < categoryData.length) {
                currentCategory = categoryData[rowIndex];
                
                // 检查是否是新分类
                if (rowIndex == 0 || categoryData[rowIndex] != categoryData[rowIndex - 1]) {
                  return Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      // 分类标题行
                      Container(
                        width: headers.length * 100.0,
                        padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
                        decoration: BoxDecoration(
                          color: Colors.blue.shade50,
                          border: Border(
                            bottom: BorderSide(color: Colors.grey.shade300),
                          ),
                        ),
                        child: Text(
                          currentCategory,
                          style: TextStyle(
                            fontSize: 13,
                            fontWeight: FontWeight.bold,
                            color: Colors.blue.shade800,
                          ),
                        ),
                      ),
                      // 数据行
                      _buildTableRow(row, headers, rowIndex),
                    ],
                  );
                }
              }
              
              return _buildTableRow(row, headers, rowIndex);
            }),
          ],
        ),
      ),
        ),
    );
  }

  /// 构建表格行
  Widget _buildTableRow(List<Widget> cells, List<String> headers, int rowIndex) {
    return Container(
      decoration: BoxDecoration(
        color: rowIndex.isEven ? Colors.white : Colors.grey.shade50,
        border: Border(
          bottom: BorderSide(color: Colors.grey.shade200),
        ),
      ),
      child: Row(
        children: List.generate(cells.length, (cellIndex) {
          return Container(
            width: _getColumnWidth(headers[cellIndex]),
            padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 10),
            child: Center(child: cells[cellIndex]),
          );
        }),
      ),
    );
  }

  /// 获取列宽
  double _getColumnWidth(String header) {
    switch (header) {
      case '序号':
        return 50;
      case '产品名称':
      case '系统名称':
      case '子系统':
      case '模块名称':
      case '服务项目':
      case '服务名称':
        return 150;
      case '参考品牌':
      case '参考型号':
        return 100;
      case '配置要求':
        return 130;
      case '政府采购编号':
        return 120;
      case '是否国产':
        return 90;
      case '项目':
        return 140;
      case '租用期限':
        return 100;
      case '单价(万元)':
      case '数量':
      case '总计(万元)':
      case '费用合计':
        return 100;
      case '备注':
        return 120;
      case '品牌':
      case '型号':
      case '配置':
        return 120;
      case '单价':
      case '总计':
      case '工作量':
      case '单价(人月)':
      case '开发费用':
      case '单位':
        return 100;
      default:
        return 100;
    }
  }

  /// 获取当前登录专家的记录
  ProjectExpert? _getCurrentExpert() {
    try {
      final currentExpertId = controller.currentExpertId;
      final experts = controller.projectExperts;
      
      // 从专家列表中找到当前专家
      for (final expert in experts) {
        if (expert.expertId == currentExpertId) {
          return expert;
        }
      }
      
      return null;
    } catch (e) {
      debugPrint('获取当前专家信息失败: $e');
      return null;
    }
  }

  // 构建按钮式Tab切换器
  Widget _buildTabSwitcher() {
    return Container(
      margin: const EdgeInsets.fromLTRB(12, 8, 12, 8),
      padding: const EdgeInsets.all(3),
      decoration: BoxDecoration(
        color: Colors.grey.shade200,
        borderRadius: BorderRadius.circular(10),
      ),
      child: Row(
        children: [
          Expanded(
            child: _buildTabButton(
              index: 0,
              icon: Icons.assignment,
              label: '项目申报书',
            ),
          ),
          const SizedBox(width: 3),
          Expanded(
            child: _buildTabButton(
              index: 1,
              icon: Icons.people,
              label: '评审专家',
            ),
          ),
          const SizedBox(width: 3),
          Expanded(
            child: _buildTabButton(
              index: 2,
              icon: Icons.description_outlined,
              label: '项目经费表',
            ),
          ),
        ],
      ),
    );
  }

  // 构建单个Tab按钮
  Widget _buildTabButton({
    required int index,
    required IconData icon,
    required String label,
  }) {
    final isSelected = _selectedIndex == index;
    
    return GestureDetector(
      onTap: () {
        setState(() {
          _selectedIndex = index;
        });
      },
      child: AnimatedContainer(
        duration: const Duration(milliseconds: 200),
        padding: const EdgeInsets.symmetric(vertical: 10),
        decoration: BoxDecoration(
          color: isSelected ? Colors.white : Colors.transparent,
          borderRadius: BorderRadius.circular(7),
          boxShadow: isSelected
              ? [
                  BoxShadow(
                    color: Colors.grey.shade300,
                    blurRadius: 3,
                    offset: const Offset(0, 1),
                  ),
                ]
              : null,
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              icon,
              size: 18,
              color: isSelected ? Colors.blue.shade600 : Colors.grey.shade600,
            ),
            const SizedBox(width: 5),
            Text(
              label,
              style: TextStyle(
                fontSize: 14,
                fontWeight: isSelected ? FontWeight.bold : FontWeight.w500,
                color: isSelected ? Colors.blue.shade600 : Colors.grey.shade600,
              ),
            ),
          ],
        ),
      ),
    );
  }

  // 底部操作按钮
  Widget _buildBottomButtons() {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        boxShadow: [
          BoxShadow(
            color: Colors.grey.shade200,
            offset: const Offset(0, -2),
            blurRadius: 8,
            spreadRadius: 0,
          ),
        ],
      ),
      child: SafeArea(
        child: Obx(() {
          // 检查当前专家是否已经完成评审
          final currentExpert = _getCurrentExpert();
          final hasCompleted = currentExpert != null && _isExpertReviewed(currentExpert);
          
          return SizedBox(
            width: double.infinity,
            child: ElevatedButton.icon(
              onPressed: hasCompleted ? null : () {
                // 直接显示评审弹出框（投票已在列表页完成）
                controller.enterReview();
              },
              icon: Icon(hasCompleted ? Icons.check_circle : Icons.gavel, size: 20),
              label: Text(
                hasCompleted ? '已完成评审' : '提交评审',
                style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w500),
              ),
              style: ElevatedButton.styleFrom(
                padding: const EdgeInsets.symmetric(vertical: 14),
                backgroundColor: hasCompleted ? Colors.green.shade600 : Colors.purple.shade600,
                foregroundColor: Colors.white,
                disabledBackgroundColor: Colors.green.shade600,
                disabledForegroundColor: Colors.white,
              ),
            ),
          );
        }),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<ShnebaoAssessmentDetialController>(
      init: ShnebaoAssessmentDetialController(),
      id: "shnebao_assessment_detial",
      builder: (_) {
        return Scaffold(
          appBar: AppBar(
            title: const Text("项目申报评审详情"),
            leading: IconButton(
              icon: const Icon(Icons.arrow_back_ios),
              onPressed: () => Get.back(),
            ),
            actions: [
              // 查看申报文件按钮
              IconButton(
                icon: const Icon(Icons.description_outlined),
                onPressed: controller.onViewDocuments,
                tooltip: '查看申报文件',
              ),
            ],
          ),
          body: SafeArea(
            child: Column(
              children: [
                // 按钮式Tab切换器
                _buildTabSwitcher(),
                
                // 内容区域
                Expanded(
                  child: IndexedStack(
                    index: _selectedIndex,
                    children: [
                      _buildProjectDetailView(),
                      _buildExpertsView(),
                      _buildProjectStepsView(),
                    ],
                  ),
                ),
              ],
            ),
          ),
          bottomNavigationBar: _buildBottomButtons(),
        );
      },
    );
  }
}
